package jersey.czjug;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

/**
 * MessageBeanWriter implementing the serialization of an individual property into
 * a stream of text/plain media type.
 */
@Provider
public class PropertyWriter implements MessageBodyWriter<PropertyBean> {
    public boolean isWriteable(Class<?> type, Type genericType,
                               Annotation[] annotations, MediaType mediaType) {
        // return true only if the desired media type is text/plain
        // and the type of the entity to be serialized is PropertyBean
        return MediaType.TEXT_PLAIN_TYPE.equals(mediaType) &&
                PropertyBean.class.isAssignableFrom(type);
    }

    public long getSize(PropertyBean t, Class<?> type, Type genericType,
                        Annotation[] annotations, MediaType mediaType) {
        // can return -1 if the size cannot be easily determined
        return -1;
    }

    public void writeTo(PropertyBean t, Class<?> type, Type genericType,
                        Annotation[] annotations, MediaType mediaType,
                        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        entityStream.write(t.toString().getBytes());
    }
}
